package com.tarena.test.lbs.es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class ESIndexTestRun {
    //使用@Before构建一个使用的客户端对象
    private RestHighLevelClient client;
    @Before
    public void initClient(){
        HttpHost httpHost=new HttpHost("localhost",9200,"http");
        RestClientBuilder builder= RestClient.builder(httpHost);
        client=new RestHighLevelClient(builder);
    }
    //创建一个索引
    @Test
    public void createIndex() throws IOException{
        CreateIndexRequest request = new CreateIndexRequest("test01");
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        //3.从响应中看到索引创建的结果
        System.out.println("创建索引："+response.isAcknowledged());
    }

    //指定索引创建条件
    @Test
    public void createShardIndex() throws Exception{
        CreateIndexRequest request = new CreateIndexRequest("test02");
        //让Test02 设置5个分片
        Settings.Builder setting = Settings.builder()
                .put("number_of_shards", 5)
                .put("number_of_replicas", 0);
        request.settings(setting);
        CreateIndexResponse response = client.indices().create(request,RequestOptions.DEFAULT);
        System.out.println("创建索引:"+response.isAcknowledged());
    }

    //删除索引
    @Test
    public void deleteIndex() throws IOException{
        DeleteIndexRequest request = new DeleteIndexRequest("test02");
        client.indices().delete(request,RequestOptions.DEFAULT);
    }

    //创建索引用Mapping映射
    @Test
    public void createMappingIndex() throws IOException{
        CreateIndexRequest request = new CreateIndexRequest("test03");
        //给请求添加一个Settings分片设置
        Settings.Builder setting =
            Settings.builder()
                    .put("number_of_shards",1)
                    .put("number_of_replicas",0);
        request.settings(setting);
        //设置添加一个Mapping
        String mapping="{\"properties\":{\"name\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"student_no\":{\"type\":\"keyword\"},\"birthday\":{\"type\":\"date\"},\"location\":{\"type\":\"geo_point\"},\"gender\":{\"type\":\"keyword\"}}}";
        request.mapping(mapping, XContentType.JSON);
        //创建索引
        client.indices().create(request,RequestOptions.DEFAULT);

    }

}
